package be.kuleuven.mume.paginas;

import java.util.List;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import be.kuleuven.mume.R;
import be.kuleuven.mume.arrayAdapters.VraagArrayAdapter;
import be.kuleuven.mume.framework.AgendaItem;
import be.kuleuven.mume.framework.Prof;
import be.kuleuven.mume.framework.Vak;
import be.kuleuven.mume.framework.Vraag;
import be.kuleuven.mume.hulpklassen.DataFetcher;
import be.kuleuven.mume.hulpklassen.HttpHelper;
import be.kuleuven.mume.hulpklassen.JSONHandler;
import be.kuleuven.mume.hulpklassen.JSONHelper;
import be.kuleuven.mume.hulpklassen.RetainListActivity;
import be.kuleuven.mume.hulpklassen.JSONParser.VragenParser;
import be.kuleuven.mume.listProxys.LastCellLoadingProxy;

public class VakInfoTab extends RetainListActivity<Vraag> implements OnItemLongClickListener, OnItemClickListener{
	private static final String TAG = "VakInfoPagina";
	private static final int ACTIVITY_ADDVRAAG=0;
	private static final int ACTIVITY_EDITVRAAG=1;
	private static final int ACTIVITY_ADDAFSPRAAK = 2;
	private static final int ADDVRAAG_ID = Menu.FIRST;
	private static final int MAILPROF_ID = ADDVRAAG_ID + 1;
	private static final int TWEETPROF_ID = MAILPROF_ID + 1;

	private TextView mProfText;
	private ListView mVragenView;
	//private DbAdapter mDbHelper;
	//private Cursor mVragenCursor;
	private Vak vak;
	private VraagArrayAdapter vraagAdapter;
	private LastCellLoadingProxy loadingProxy;
	private List<Vraag> vragen;
	private DataFetcher<Vraag> datafetcher;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);  	  	
		setContentView(R.layout.vakinfopagina);
		
		//mDbHelper = new DbAdapter(this);
		Bundle extras = getIntent().getExtras();
		vak = (Vak)extras.getSerializable("VAK");
		
		mVragenView = (ListView) findViewById(R.id.vragenlijst);
		vragen = getItems();
		vraagAdapter = new VraagArrayAdapter(this, vragen);
		loadingProxy = new LastCellLoadingProxy(vraagAdapter);
		loadingProxy.noDataString_ID = R.string.geen_vragen;
		
		mVragenView.setAdapter(loadingProxy);
		mVragenView.setOnItemLongClickListener(this);
		mVragenView.setOnItemClickListener(this);

		final Prof p = vak.getProf();
		mProfText = (TextView)findViewById(R.id.professor);
		if(vak.hasProf())
			mProfText.setText(p.getName());
		else
			mProfText.setText(R.string.no_prof);

		ImageButton contact = (ImageButton)findViewById(R.id.contact_btn);
		if(!vak.hasProf() ||  p.countContactMethods() < 1)
			contact.setVisibility(View.INVISIBLE);
		else {
			contact.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					if(p.countContactMethods() < 2)
					{
						if(p.hasMail())
							sendMailIntent(p);
						if(p.hasTwitter())
							sendTwitterIntent(p);
					}

					showChooserDialog(p);
				}
			});
		}

		String url = Vraag.getUrl(vak.getVakId());
		VragenParser parser = new VragenParser();

		datafetcher = new DataFetcher<Vraag>(parser, 
				url, mVragenView, vragen, this.getBaseContext()){
			public void DataReceived(){
				if(!datafetcher.hasMoreData()){
					loadingProxy.setIsLoading(false);
				}
				vraagAdapter.notifyDataSetChanged();
			}
		};
	}

	private void showChooserDialog(final Prof p) {
		String[] items = {"Mail", "Twitter", "Maak Afspraak"};
		AlertDialog.Builder builder = new AlertDialog.Builder(VakInfoTab.this);
		builder.setTitle("Contact");
		builder.setItems(items, new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialogInterface, int item) {
				switch(item){
				case 0:
					sendMailIntent(p);
					break;
				case 1:
					sendTwitterIntent(p);
					break;
				case 2:
					createAfspraakIntent(p);
					break;
				default :
					Log.e(TAG, "Selection not found for contact list.");
				}
				return;
			}
		});
		builder.create().show();
	}

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if(position < vraagAdapter.getCount()){
			Vraag vraag = vraagAdapter.getItem(position);
			Intent i = new Intent(VakInfoTab.this, AntwoordenPagina.class);
			i.putExtra(Vraag.VRAAG, vraag);

			startActivity(i);
		}
	}

	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		if(position < vraagAdapter.getCount()) {
			Vraag vraag = vraagAdapter.getItem(position);
			Intent i = new Intent(VakInfoTab.this, VraagEditPagina.class);
			i.putExtra(Vraag.VRAAG, vraag);
			i.putExtra(Vak.KEY_ID, vak.getVakId());
			startActivityForResult(i, ACTIVITY_EDITVRAAG);

			return true;
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, ADDVRAAG_ID,0, R.string.nieuw_vraag);
		if(this.vak.hasProf()){
			Prof p = vak.getProf();
			if(p.hasMail())
				menu.add(0,MAILPROF_ID,0,R.string.mail_prof);
			if(p.hasTwitter())
				menu.add(0,MAILPROF_ID,0,R.string.tweet_prof);
		}
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getItemId()) {
		case ADDVRAAG_ID:
			Intent i = new Intent(VakInfoTab.this, VraagEditPagina.class);
			i.putExtra(Vak.KEY_ID, vak.getVakId());
			startActivityForResult(i, ACTIVITY_ADDVRAAG);
			return true;
		case MAILPROF_ID:
			sendMailIntent(vak.getProf());
			return true;
		case TWEETPROF_ID:
			sendTwitterIntent(vak.getProf());
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}

	private void sendTwitterIntent(Prof p) {
		Intent sendIntent = new Intent(Intent.ACTION_SEND); 
		sendIntent.putExtra(Intent.EXTRA_TEXT, "@" + vak.getProf().getTwitterName()); 
		sendIntent.setType("application/twitter");
		startActivity(Intent.createChooser(sendIntent, "Tweet!")); 
	}

	private void sendMailIntent(Prof p) {
		try{
			final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
			emailIntent .setType("plain/text");
			emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{vak.getProf().getMail()});
			//emailIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, mySubject);
			startActivity(Intent.createChooser(emailIntent, "Choose mail app"));
		}catch(ActivityNotFoundException e){
			Toast.makeText(this, R.string.geen_mail_app, 10).show();
		}
	}
	
	private void createAfspraakIntent(Prof p) {
		Intent intent = new Intent(this, AgendaEditPagina.class);
		intent.putExtra(AgendaEditPagina.PROF, p);
		startActivityForResult(intent, ACTIVITY_ADDAFSPRAAK);
	}

	/* private void toonVragen() {	


		 // Gebruik SQLite
//		 mDbHelper.open();
//		 mVragenCursor = mDbHelper.fetchAllVragen(3);
//		 
//		 Cursor c = mVragenCursor;
//	     startManagingCursor(mVragenCursor);
//		 
//	     vragen.clear();
//	     for(int i = 0; i < c.getCount(); i++) {
//	    	 c.moveToPosition(i);
//	    	 String title = c.getString(c.getColumnIndexOrThrow(DbAdapter.KEY_ONDERWERP));
//	    	 String body = c.getString(c.getColumnIndexOrThrow(DbAdapter.KEY_VRAAG));
//	    	 Vraag vraag = new Vraag(title, body, vak.getId());
//	    	 vragen.add(vraag);
//	     }
//
//	     noteAdapter.notifyDataSetChanged();
//	     mDbHelper.close();
	 }
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if(intent == null)
			return;

		Bundle extras = intent.getExtras();

		Vraag vraag;
		switch(requestCode) {
		case ACTIVITY_ADDVRAAG:
			vraag = (Vraag)extras.get(Vraag.VRAAG);
			postVraag(vraag,Vraag.ADD_URL);
			break;
		case ACTIVITY_EDITVRAAG:
			vraag = (Vraag)extras.get(Vraag.VRAAG);
			postVraag(vraag, Vraag.UPDATE_URL);
			break;
		case ACTIVITY_ADDAFSPRAAK:
			AgendaItem item = (AgendaItem)extras.get(AgendaItem.AGENDA_ID);
			JSONObject obj = JSONHelper.createAfspraak(item);
			post(AgendaItem.ADD_URL, obj);
		}
		// Gebruik SQLite database
		//			 mDbHelper.open();
		//			 mDbHelper.createVraag(title, body, vak.getId());
		//			 Vraag note = new Vraag(title, body);
		//			 notes.add(note);
		//			 noteAdapter.notifyDataSetChanged();
		//			 mDbHelper.close();
		//checkEmptyVragenLijst();


	}

	private void postVraag(Vraag vraag, String url) {
		JSONObject obj = JSONHelper.createVraag(vraag);
		
		post(url, obj);

		if(!vragen.contains(vraag))
			vragen.add(0,vraag);
		vraagAdapter.notifyDataSetChanged();
	}

	private void post(String url, JSONObject obj) {
		JSONHandler h = new JSONHandler() {
			
			@Override
			public void handelJSON(JSONObject obj) {
				if(obj.has("error"))
					Toast.makeText(VakInfoTab.this, R.string.serverError, 10).show();
			}
		};
		
		HttpHelper.doPostInThread(url, obj, this.getBaseContext(), h);
	}
}
